package com.clouddot.baipai.util.viewUtil.cameraView;

import android.app.Activity;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


import com.clouddot.baipai.http.BanPaiRetrofitHelper;
import com.clouddot.baipai.infrastructure.environment.Env;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 王士源 on 2017/10/30.
 */

public class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.PictureCallback {
    private SurfaceHolder holder;
    private Camera camera;
    private boolean af;
    private boolean isUse = false;

    private Activity activity;

    public CameraView(Activity context) {//构造函数
        super(context);
//        Toast.makeText(context, "拍照中..." , Toast.LENGTH_SHORT).show();
        this.activity = context;

        holder = getHolder();//生成Surface Holder  
        holder.addCallback(this);

        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//指定Push Buffer
    }
    public  void closeCamera() {
        try {
            camera.stopPreview();
            camera.release();
            camera = null;
        } catch (Exception e) {
        }

    }
    public void surfaceCreated(SurfaceHolder holder) {//Surface生成事件的处理  
        try {

            //closeCamera();
            camera = Camera.open();
            Camera.Parameters p = camera.getParameters();
            p.setPictureSize(1500, 2000); //设置照片分辨率，太大上传不了
            camera.setParameters(p);

            camera.setPreviewDisplay(holder);
            //camera.setDisplayOrientation(90);  
        } catch (Exception e) {
            Env.error(e);
        }
    }

    private void data2file(byte[] w, String fileName) throws Exception {//将二进制数据转换为文件的函数
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(fileName);
            out.write(w);
            out.close();
        } catch (Exception e) {
            if (out != null)
                out.close();
            throw e;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {//Surface改变事件的处理
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(width, height);
//        camera.setParameters(parameters);//设置参数

        camera.startPreview();//开始预览
        new MyThread().start();//这个线程实现拍照保存上传
        //camera.autoFocus(null);  
        // camera.takePicture(null, null, this);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

    }

    class MyThread extends Thread implements Camera.PictureCallback {
        @Override
        public void run() {
            super.run();
            camera.autoFocus(null);
            camera.takePicture(null, null, this);
//            while (true) {
//                System.out.println("拍照线程wu异常");
//                try {
//                    sleep(50000);//20秒执行一次
//                } catch (InterruptedException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }

        }

        @Override
        public void onPictureTaken(byte[] data, Camera cameras) {
            // TODO Auto-generated method stub

            try {
                String path = android.os.Environment.getExternalStorageDirectory() + "/test.jpg";
                Log.v("path", path);
                data2file(data, path);    //到这步为止完成了自动拍照并保存，下面这个线程是上传的 想要触摸拍照的话要改写下的onTouchEvent方法，我这不用

                new Thread() {
                    @Override
                    public void run() {
                        Map<String, String> params = new HashMap<String, String>();
                        Map<String, File> files = new HashMap<String, File>();

                        try {
                            params.put("folder","cardsigner");
                            files.put("Filedata",new File(android.os.Environment.getExternalStorageDirectory() + "/test.jpg"));
                            String fileinfo = BanPaiRetrofitHelper.getInstance(Env.getContent()).doFilePost("http://" + Env.getAppContext().IP + "/YDS/UploadFile", params, files);
                            activity.getIntent().putExtra("back", fileinfo);
                            activity.setResult(123, activity.getIntent());
                            closeCamera();
                            activity.finish();
                        }
                        catch (Exception ex){
                            Env.error(ex);

                            return;
                        }
                    }

                }.start();

            } catch (Exception e) {
                e.printStackTrace();
                Env.error(e);

                activity.finish();
            }
            //camera.startPreview();
        }
    }
}
